//
// Created by yonghu0 on 25-10-30.
//

#include "Config.h"
#include <fstream>
#include <string>  //getline头文件

Config::Config()
{
    const char *config_file_path = "../conf/oj.conf";
    LoadConfig(config_file_path);
}

Config &Config::GetInstance()
{
    static Config instance;
    return instance;
}

bool Config::LoadConfig(const char *config_file_path)
{
    std::ifstream config_file(config_file_path);
    if (!config_file.is_open())
    {
        return false;
    }
    std::string line;
    while (std::getline(config_file, line))
    {
        //去除两端空格
        Trim(line);

        //判断是否是注释
        if (line.front() == '#')
            continue;

        //处理尾部注释
        size_t comment_pos = line.find('#');
        if (comment_pos != std::string::npos)
        {
            line = line.substr(0, comment_pos);
        }

        //判断是否有=号
        size_t pos = line.find("=");
        if (pos == std::string::npos)
            continue;

        //以等号分割key，value
        std::string key = line.substr(0, pos);
        std::string value = line.substr(pos + 1);
        //去除key，value两端空格
        Trim(key);
        Trim(value);
        //保存到map
        m_config_map[key] = value;
    }
    //手动刷新缓冲区
    config_file.close();

    return true;
}

std::string Config::GetValue(const std::string &key)
{
    if (m_config_map.find(key) != m_config_map.end())
        return m_config_map[key];
    else
        return "";
}

void Trim(std::string &str)
{
    //从头查找第一个不是空格的字符,substr
    size_t pos = str.find_first_not_of(' ');
    //全是空格或没有字符
    if (pos == std::string::npos)
    {
        str = "";
        return;
    }
    str = str.substr(pos);

    //从尾查找第一个不是空格的字符，substr
    size_t lpos = str.find_last_not_of(' ');
    str = str.substr(0, lpos + 1);
}
